<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/12/4
 * Time: 14:59
 */

namespace app\zyhsapi\model;

use app\zyhsapi\service\CacheZyhs;
use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsUserAddQuestion extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_user_add_question';

    protected $cacheModel = 'question_answer.add_question';

    /**
     * 新增问答信息
     */
    public function SaveData($taskId, $data)
    {
        try
        {
            $id = $this->insertGetId($data);
            // 添加至我的问答-提问列表
            if ($data['status'] === 2)
            {   // 添加至追问列表
                $this->listDataAdd($taskId, [$id => $data['pay_time']]);
            }
            return (int)$id;
        }
        catch (\Exception $e)
        {
            Log::write('问答 ZyhsUserAddQuestion model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return 0;
        }
    }

    /**
     * 更新问答信息
     */
    public function UpdateData($id, $data)
    {
        try
        {
            $this->where(['id' => $id])->update($data);

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $where = ['id' => ['in', $ids]];
            } else
            {
                $where = ['task_id' => $type[0], 'status' => ['in', [2, 4, 5, 6, 7, 8]]];
            }
            $data = $this
                ->where($where)
                ->order('pay_time ', $sortType)
                ->column('astr_id,task_id,status,activity_discount,order_num,question,create_time,answer_content,answer_duration,reply_time,pay_time,cannel_tag_name,cannel_cause,supplement_answer,uid,good_amount', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $orderId => $questionItemData)
        {
            $resData[$orderId] = arrayKeyData2int($questionItemData, ['astr_id', 'task_id', 'create_time', 'status', 'answer_duration', 'reply_time', 'id', 'pay_time', 'uid']);

            if (isset($questionItemData['supplement_answer']))
            {
                $resData[$orderId]['supplement_answer'] = $questionItemData['supplement_answer'] ? json_decode($questionItemData['supplement_answer'], true) : [];
            }
        }

        return $resData;
    }

    /**
     * 获取当前问答问题待解答的追问数据
     * @param $taskId
     * @return array
     */
    public function getAddQuestionByNotAnswer($taskId)
    {
        try
        {
            return $this->where(['task_id' => $taskId, 'status' => 2])->order('id desc')->findOrFail()->toArray();
        }
        catch (\Exception $e)
        {
            Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }
    }

    /**
     * 获取问题追问   信息
     */
    public function getQuestionAddQuestionInfo($taskId)
    {
        request()->get(['page' => -1]);
        $pageData = $this->getListPage($taskId, 'id', [], 0, 'asc');

        $resData = [];
        foreach ($pageData['data'] as $datum)
        {
            if (in_array((int)$datum['status'], [2, 4, 5, 6, 7, 8], true))
            {
                $resData[] = [
                    'id' => (int)$datum['id'],
                    'task_id' => $datum['task_id'],
                    'answer_duration' => (int)$datum['answer_duration'],
                    'order_num' => $datum['order_num'],
                    'reply_time' => (int)$datum['reply_time'],
                    'create_time' => (int)$datum['create_time'],
                    'status' => (int)$datum['status'],
                    'pay_time' => (int)$datum['pay_time'],
                    'question' => $datum['question'],
                    'activity_discount' => $datum['activity_discount'],
                    'answer_content' => $datum['answer_content'],
                    'astr_id' => (int)$datum['astr_id'],
                    'cannel_cause' => $datum['cannel_cause'],
                    'cannel_tag_name' => $datum['cannel_tag_name'],
                    'supplement_answer' => $datum['supplement_answer'] ? json_decode($datum['supplement_answer'], true) : []
                ];
            }
        }

        return $resData;
    }

    /**
     * 获取当前问题追问次数
     * @param $taskId
     * @param int $filterInvalid 是否过滤无效提问【占星师申述取消，追问回复超时已取消，用户申述通过退款】 1=>过滤 0=>不过滤
     * @return int
     * @throws \Exception
     */
    public function getQuestionAddQuestionNum($taskId, $filterInvalid = 0): int
    {
        request()->get(['page' => -1]);
        $pageData = $this->getListPage($taskId, 'id', [], 0, 'asc');
        $statusList = $filterInvalid === 1 ? [2, 4] : [2, 4, 5, 6, 7, 8];
        $num = 0;
        foreach ($pageData['data'] as $datum)
        {
            if (in_array($datum['status'], $statusList, false))
            {
                $num++;
            }
        }

        return $num;
    }

    /**
     * 设置 追问 临时缓存
     * @param int $taskId
     * @param array $data
     * @return void
     * @throws \RedisException
     */
    public function setTmpAddQuestionData(int $taskId, array $data)
    {
        $addQuestionDataStr = json_encode($data, JSON_UNESCAPED_UNICODE);
        CacheZyhs::set('question_answer:add_question:' . $taskId, $addQuestionDataStr, 7200);
    }

    /**
     * 获取 追问 临时缓存
     * @param int $taskId
     * @return array
     * @throws \Exception
     */
    public function getTmpAddQuestionData(int $taskId)
    {
        $data = CacheZyhs::get('question_answer:add_question:' . $taskId, null);
        if ($data)
        {
            return json_decode($data, true);
        } else
        {
            return [];
        }
    }

    /**
     * 删除 追问 临时缓存
     * @param int $taskId
     * @return void
     * @throws \RedisException
     */
    public function rmTmpAddQuestionData(int $taskId)
    {
        CacheZyhs::rm('question_answer:add_question:' . $taskId);
    }

    /**
     * 追问退款
     * @param int $addId
     * @param string $reason
     * @return array
     * @throws \Exception
     */
    public function refund(int $addId, string $reason)
    {
        $addIno = $this->getInfoById($addId, ['order_num', 'good_amount']);
        (new ZyhsOrders())->refund($addIno['order_num'], $addIno['good_amount'] / 10, $reason);
        return [
            'status' => true,
            'refund_amount' => $addIno['good_amount']
        ];
    }
}
